<?php

namespace app\admin\controller\xilujob;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
    protected $noNeedRight = ['chart_data'];
    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $this->view->assign([
            'todaycompany'    => \app\admin\model\xilujob\CompanyProfile::whereTime('createtime','d')->count('id'),
            'todaymember'    => \app\admin\model\xilujob\Member::whereTime('createtime','d')->count('id'),
            'todaypackage'    => \app\admin\model\xilujob\PackageOrder::whereTime('paytime','d')->where('pay_status',2)->count('id'),
            'todaypackagesum'    => \app\admin\model\xilujob\PackageOrder::whereTime('paytime','d')->where('pay_status',2)->sum('pay_price'),
            'todayjob'    => \app\admin\model\xilujob\Job::whereTime('createtime','d')->count('id'),
            'todayapply'    => \app\admin\model\xilujob\JobApply::whereTime('createtime','d')->count('id'),
            'todaydownload'    => \app\common\model\xilujob\ResumeDownload::whereTime('createtime','d')->count('id'),
            'todayrefresh'    => \app\common\model\xilujob\JobRefreshLog::whereTime('createtime','d')->count('id'),

            'totalcompany'    => \app\admin\model\xilujob\CompanyProfile::count('id'),
            'totalmember'    => \app\admin\model\xilujob\Member::count('id'),
            'totalpackage'    => \app\admin\model\xilujob\PackageOrder::where('pay_status',2)->count('id'),
            'totalpackagesum'    => \app\admin\model\xilujob\PackageOrder::where('pay_status',2)->sum('pay_price'),
            'totaljob'    => \app\admin\model\xilujob\Job::count('id'),
            'totalapply'    => \app\admin\model\xilujob\JobApply::count('id'),
            'totaldownload'    => \app\common\model\xilujob\ResumeDownload::count('id'),
            'totalrefresh'    => \app\common\model\xilujob\JobRefreshLog::count('id'),

            'sevendau'        => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'       => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'        => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'        => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'     => count($dbTableList),
            'dbsize'          => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'attachmentnums'  => Attachment::count(),
            'attachmentsize'  => Attachment::sum('filesize'),
            'picturenums'     => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'     => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        return $this->view->fetch();
    }


    /**
     * 获取表格数据
     * @return array
     */
    public function chart_data(){
        $param = $this->request->param();

        //日期类型
        $dateType = isset($param['dateType'])?$param['dateType']:'day';

        //默认最近7天
        $dateRange = !empty($param['dateRange'])?$param['dateRange']:'';
        if(!$dateRange){
            $dateRange = datetime(\fast\Date::unixtime('day', -29)) . ' - ' . date('Y-m-d 23:59:59');
        }else if($dateType == 'month'){
            $dateRange = datetime(\fast\Date::unixtime('month', -12)) . ' - ' . date('Y-m-d 23:59:59');
        }else if($dateType == 'year'){
            $dateRange = datetime(\fast\Date::unixtime('year', -6)) . ' - ' . date('Y-m-d 23:59:59');
        }

        list($start, $end) = explode(' - ', $dateRange);
        $starttime = strtotime($start);
        $endtime = strtotime($end);

        $xAxis = [];
        $format = '';
        switch($dateType){
            case 'day': //天
                $day = ceil(($endtime-$starttime)/86400);
                for ($i = 0; $i < $day; $i++) {
                    $xAxis[] = date("Y-m-d", $starttime+$i*86400);
                }
                $format = '%Y-%m-%d';
                break;
            case 'month': //月
                $_start = $starttime;
                $endMonth = date('Y-m', $endtime);
                while (($startMonth = date('Y-m', $_start)) <= $endMonth) {
                    $xAxis[] = $startMonth;
                    $_start = strtotime('next month', $_start);
                }
                $format = '%Y-%m';
                break;
            case 'year': //年
                $_start = $starttime;
                $endYear = date('Y', $endtime);
                while (($startYear = date('Y', $_start)) <= $endYear) {
                    $xAxis[] = $startYear;
                    $_start = strtotime('next year', $_start);
                }
                $format = '%Y';
                break;
            default:
                $this->error('未知的日期类型');
        }


        //查询数据
        $list = array_fill_keys($xAxis, 0);
        $legend = $series = [];
        switch($param['type']){
            case 'order':
                $legend = ['企业增长曲线图','求职者曲线图','套餐订单数', '套餐金额数'];
                foreach($legend as $v){
                    $series[] = $list;
                }
                $companyModel = new \app\admin\model\xilujob\CompanyProfile();
                //企业数
                $field = "from_unixtime(createtime, '{$format}') AS dates, COUNT(id) as num";
                $map = [
                    'createtime'    => ['between', [$starttime, $endtime]]
                ];
                $lists = $companyModel->field($field)->where($map)->group('dates')->select();
                foreach($lists as $v){
                    $series[0][$v['dates']] = $v['num'];
                }
                //求职者数
                $memberModel = new \app\common\model\xilujob\Member();
                $field2 = "from_unixtime(createtime, '{$format}') AS dates, COUNT(id) as num";
                $map2 = [
                    'createtime'       => ['between', [$starttime, $endtime]],
                ];
                $lists2 = $memberModel->field($field2)->where($map2)->group('dates')->select();
                foreach($lists2 as $v){
                    $series[1][$v['dates']] = $v['num'];
                }
                //订单数
                $packageOrderModel = new \app\admin\model\xilujob\PackageOrder();
                $field3 = "from_unixtime(paytime, '{$format}') AS dates, COUNT(id) as num";
                $map3 = [
                    'pay_status' => 2,
                    'paytime'    => ['between', [$starttime, $endtime]]
                ];
                $lists3 = $packageOrderModel->field($field3)->where($map3)->group('dates')->select();
                foreach($lists3 as $v){
                    $series[2][$v['dates']] = $v['num'];
                }
                //订单金额
                $field4 = "from_unixtime(paytime, '{$format}') AS dates, SUM(pay_price) as num";
                $map4 = [
                    'pay_status'    => 2,
                    'paytime'       => ['between', [$starttime, $endtime]],
                ];
                $lists5 = $packageOrderModel->field($field4)->where($map4)->group('dates')->select();
                foreach($lists5 as $v){
                    $series[4][$v['dates']] = $v['num'];
                }

                break;
        }

        foreach ($series as $k => &$v){
            $v = array_values($v);
        }
        $result = ['legend'=>$legend, 'xAxis'=>$xAxis, 'series'=>$series, 'range'=>$dateRange];

        $this->success('', null, $result);
    }

}
